package com.ckcool.api.util;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.*;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import lombok.extern.slf4j.Slf4j;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;

import org.springframework.stereotype.Component;

import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;

/**
 * 调用js代码提供sql和服务支持
 *
 * @author
 */
@Slf4j
@Component
public class ExecuteScriptEngine {
    @Resource
    private RestTemplate RT;
    /**
     * 发送请求
     *
     * @param url     请求地址
     * @param method  请求方式
     * @param headers 请求头  可空
     * @param params  请求body参数 可空
     * @return ResponseEntity<responseType>
     */
    public <T> T httpRequest(String url, HttpMethod method, Object params, HttpHeaders headers, Class<T> clazz) {
        try {
            if (StrUtil.isEmpty(url)) {
                Assert.isTrue(false, "baseUrl 不能为空");
            }
            if (ObjectUtil.isEmpty(method)) {
                Assert.isTrue(false, "method 不能为空");
            }
            if (ObjectUtil.isEmpty(headers)) {
                headers = new HttpHeaders();
            }
            String contentType = MapUtil.getStr(headers, Header.CONTENT_TYPE.getValue());
            if (StrUtil.isBlank(contentType)) {
                headers.set(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue());
            }
            // 请求体
            String body = "";
            if (ObjectUtil.isNotEmpty(params)) {
                if (params instanceof JSONObject || params instanceof Map) {
                    body = JSON.toJSONString(params, SerializerFeature.WriteMapNullValue);
                } else {
                    body = params.toString();
                }
            }
            // 发送请求
            HttpEntity<String> request = new HttpEntity<>(body, headers);
            T res = RT.exchange(url, method, request, clazz).getBody();
            return res;
        } catch (Exception e) {
            Assert.isTrue(false, "HTTP调用错误 ，错误提示:" + StrUtil.subPre(ExceptionUtil.getRootCauseMessage(e), 1000));
        }
        return null;
    }

    /**
     * 发送请求
     *
     * @param url     请求地址
     * @param method  请求方式
     * @param headers 请求头  可空
     * @param params  请求body参数 可空
     * @return ResponseEntity<responseType>
     */
    public Object httpRequest(String url, HttpMethod method, Object params, HttpHeaders headers) {
        return httpRequest(url, method, params, headers, String.class);
    }


}


